package com.example.educationalsystem.common.util;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * @Description: 上传文件工具类//描述
 * @ClassName:FileUntil//类名
 * @Author:zpc//作者
 * @Date: 2022/10/9 12:17
 */
@Service
public class UploadFileService {
    @Value("${file.baseUrl}")
    private String baseUrl;
    /**
     * @Param : UPLOADS_PATH
     * @Description: 上传路径
     */
    @Value("${file.uploadsDir}")
    public  String uploadsDir;


    public String uploads(MultipartFile file, String tagPath) throws IOException {

        //获取文件后缀
        final String filenameSuffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf('.') + 1);
        //生成不重复文件名
        String filename = UUID.randomUUID().toString().replace(".", "") + "." + filenameSuffix;
        //通过日期生成目录
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
        String datePath = dateFormat.format(new Date());
        //最终目录
        File targetPath = new File(uploadsDir + "//" + tagPath, datePath);
        if (!targetPath.exists()) targetPath.mkdirs();
        //生成文件路径
        File descFile = new File(targetPath, filename);
        //文件写入
        System.out.println(uploadsDir);
        file.transferTo(descFile);
        String url = baseUrl + tagPath + "/" + datePath + "/" + filename;
        return url;
    }


}
